<template>
  <div>
    <div class="ueditor">
      <script :id="ids" :defaultMsg="writeMsg" type="text/plain"></script>
    </div>

    <!--项目编号-->
  </div>
</template>

<script>
// import '../../../static/js/jquery-1.9.1.min.js'
import '../../../public/static/ueditor/ueditor.config.js'
import '../../../public/static/ueditor/ueditor.all.js'
import '../../../public/static/ueditor/lang/zh-cn/zh-cn.js'

// 引入公式插件
import '../../../public/static/ueditor/kityformula-plugin/addKityFormulaDialog.js'
import '../../../public/static/ueditor/kityformula-plugin/getKfContent.js'
import '../../../public/static/ueditor/kityformula-plugin/defaultFilterFix.js'

export default {
  name: 'UEditor',
  props: {
    id: {
      type: String
    },
    config: {
      type: Object
    },
    writeMsg: {
      type: String
    },
    inputBand: {
      type: String
    }
  },
  components: {
    // Editdiv:resolve => {require(['../Editdiv'],resolve)},
  },
  directives: {
    // 自定义指令获取焦点
    myfocus: {
      inserted: function (el, binding) {
        el.focus()
      }
    }
  },
  data () {
    return {
      editor: null,
      isinit: false,

      ids: '',
      sel: {},
      range: {} // 获取鼠标焦点的位置
    }
  },

  mounted () {
    this.ids = 'editor' + Math.random() * 100000000000000000 // 每个编辑器生成不同的id,以防止冲突
    // 点击工具栏添加横线调用static/ueditor/ueditor.all.js这个里面调用的
    var that = this

    //   console.log(this.ids)
    this.$nextTick(() => {
      // 避免在切换到填空题再切回来找不到dom而报offsetWidth undefined
      const _this = this
      _this.editor = window.UE.delEditor(_this.ids)
      window.UE.delEditor(_this.ids)
      //           console.log(this.ids)
      _this.editor = window.UE.getEditor(_this.ids, _this.config)

      _this.editor.addListener('ready', function () {
        _this.isinit = true

        // 监听编辑器内容的变化contentChange.有时候输入内容少就监听不到，这里用监听失去焦点
        window.UE.getEditor(_this.ids).addListener('blur', function () {
          const content = window.UE.getEditor(_this.ids).getContent()
          // 编辑器内容有变动,通知父组件接收值
          if (_this.inputBand === 'true') {
            _this.$emit('input', content)
          }
        })
      })
    })
  },
  destoryed () {
    this.editor.destory()
  },
  methods: {
    getUEContent: function () {
      return this.editor.getContent()
    },
    getContentTxt: function () {
      return this.editor.getContentTxt()
    },
    setUEContent: function (val) {
      if (this.editor && this.editor.isReady) {
        const _this = this
        setTimeout(function () {
          // 过段时间在加载
          _this.editor.setContent(val)
        }, 600)
      } else {
        const _this = this
        setTimeout(function () {
          // 过段时间在加载
          _this.setUEContent(val)
        }, 600)
      }
    },
    setUEDsiabled: function () {
      // 编辑器不可编辑
      return this.editor.setDisabled()
    },
    // 获取焦点的方程式框
    setFocusInputMask (key) {
      this.focusInputMasks = key
    },
    // 失去焦点时获取位置
    setBlur () {
      this.sel = window.getSelection()
      this.range = this.sel.getRangeAt(0)
      this.range.deleteContents()
    },
    // 在焦点处插入内容
    insertHtmlAtCaret (html, type) {
      // html要插入的内容。type type1插入矩阵和方程。type2插入弧长
      if (window.getSelection) {
        // IE9 and non-IE
        if (this.sel.getRangeAt && this.sel.rangeCount) {
          var el = document.createElement('div')
          el.innerHTML = html
          var frag = document.createDocumentFragment()
          var node
          var lastNode
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node)
          }
          this.range.insertNode(frag)
          // Preserve the selection
          if (lastNode) {
            this.range = this.range.cloneRange()
            this.range.setStartAfter(lastNode)
            this.range.collapse(true)
            this.sel.removeAllRanges()
            this.sel.addRange(this.range)
          }
        }
      } else if (document.selection && document.selection.type !== 'Control') {
        // IE < 9
        document.selection.createRange().pasteHTML(html)
      }

      if (type === 'type1') {
        // 矩阵
        // this.fxAnswer[this.focusInputMasks] = $('.fxAnswer')
        //   .eq(this.focusInputMasks)
        //   .html()
      } else {
        // 弧长
        // this.widehatHtml = $('#child').html()
      }
    },
    // 清除复杂公式里面所有的内容
    clearAllContent () {
      this.superscript_bottom = ''
      this.superscript_top = ''
      this.subscript_bottom = ''
      this.subscript_top = ''
      this.allscript_bottom = ''
      this.allscript_center = ''
      this.allscript_top = ''
      this.log_center = '' // 对数
      this.log_top = ''
      this.log_bottom = ''

      this.sign_left = ''
      this.sign_right = ''
      this.fraction_fenzi = ''
      this.fraction_fenmu = ''
      this.widehat = ''
      this.overline = ''
      this.angle = ''
      this.circ = ''
    },
    // 点击复杂公式里面的子公式图标
    showMask (i, j) {
      this.show = i
      this.type = j
      this.clearAllContent() // 清空内容
      if (i === 0 || i === 4) {
        // 插入方程式，矩阵
        this.fxAnswer = []
        this.fxAnswer2 = []
        this.inputNumber = []
        this.fxShow2 = false // 第二个不显示
        this.widehatHtml = ''
        var promptMsg, promptErrorMsg
        if (i === 0) {
          this.showFx = true
          promptMsg = '请输入方程式的个数'
          promptErrorMsg = '请输入方程式的个数1-9'
        } else if (i === 4) {
          this.showFx = false
          promptMsg = '请输入矩阵的个数'
          promptErrorMsg = '请输入矩阵的个数1-9'
        }
        this.$prompt(promptMsg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^([1-9])$/,
          inputErrorMessage: '请输入1-9位数字',
          inputPlaceholder: promptErrorMsg,
          inputValue: '1',
          closeOnClickModal: false // 点击遮罩不关闭
        })
          .then(({ value }) => {
            for (var j = 0; j < value; j++) {
              this.inputNumber.push(j)
            }
            this.fxShow = true
          })
          .catch(() => {})
      } else {
        // 必须先点方程式再输入右边的辅助公式,
        if (
          this.type !== 1 &&
          this.inputNumber.length === 0 &&
          this.fxShow2 !== true
        ) {
          this.$message.error('这是辅助公式,请先插入|前的公式')
        } else if (
          this.type === 2 &&
          (this.inputNumber.length !== 0 || this.fxShow2 === true)
        ) {
          // 辅助公式
          this.clickShow = true
        } else if (this.type === 1 && this.show > 4) {
          // 主要公式5弧长,6平均数
          this.fxShow = false
          this.fxShow2 = true
          this.clickShow = true
        } else {
          // 符号公式直接输入
          if (this.show === 31) {
            this.formula = '>'
          } else if (this.show === 32) {
            this.formula = '< '
          } else if (this.show === 33) {
            this.formula = '\\geqslant '
          } else if (this.show === 34) {
            this.formula = '\\leqslant '
          } else if (this.show === 35) {
            this.formula = '\\pm '
          } else if (this.show === 36) {
            this.formula = '\\mp '
          } else if (this.show === 37) {
            this.formula = '\\approx '
          } else if (this.show === 38) {
            this.formula = '\\cong '
          } else if (this.show === 39) {
            this.formula = '\\propto '
          } else if (this.show === 41) {
            this.formula = '+'
          } else if (this.show === 42) {
            this.formula = '-'
          } else if (this.show === 43) {
            this.formula = '\\times '
          } else if (this.show === 44) {
            this.formula = '\\div'
          } else if (this.show === 45) {
            this.formula = '='
          } else if (this.show === 40) {
            // 输入编号
            this.$prompt('请输入编号', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^\d{1,}$/,
              inputErrorMessage: '请输入数字编号',
              inputValue: 1,
              closeOnClickModal: false // 点击遮罩不关闭
            })
              .then(({ value }) => {
                this.formula = `\\textcircled{{${value}}}`
                this.getFormale()
              })
              .catch(() => {})
          } // 结束40
          if (this.show !== 40) {
            this.getFormale()
          }
        }
      }
    },
    /// /符号公式
    getFormale () {
      if (this.fxShow === true) {
        // 直接输入进入矩阵或者方程，显示输入的内容
        if (this.show === 42 || this.show === 45) {
          // 如果是减号等号就不保存在img里面。否则显示的像是下划线
          this.fxAnswer[this.focusInputMasks] = this.formula
        } else {
          this.fxAnswer[this.focusInputMasks] =
            "<img src='http://latex.codecogs.com/gif.latex?" +
            this.formula +
            "' data-latex='" +
            this.formula +
            "' class='kfformula'/>"
        }
        this.$set(
          this.fxAnswer,
          this.focusInputMasks,
          this.fxAnswer[this.focusInputMasks]
        )
        this.insertHtmlAtCaret(this.fxAnswer[this.focusInputMasks], 'type1')
      } else if (this.fxShow2 === true) {
        /// /弧长，平均数及之后的
        if (this.show === 42 || this.show === 45) {
          // 如果是减号等号就不保存在img里面。否则显示的像是下划线
          this.widehatHtml = this.formula
        } else {
          this.widehatHtml =
            "<img src='http://latex.codecogs.com/gif.latex?" +
            this.formula +
            "' data-latex='" +
            this.formula +
            "' class='kfformula'/>"
        }
        this.insertHtmlAtCaret(this.widehatHtml, 'type2')
      }
    },
    // 点击delete删除这个方程式的框
    deleteInput (key) {
      this.inputNumber.splice(key, 1)
    },
    // 上标根号分数的提交
    clickSubmit () {
      this.clickLoading = true
      if (this.show === 1) {
        // 上标
        if (this.superscript_bottom === '' || this.superscript_top === '') {
          this.formula = ''
        // eslint-disable-next-line brace-style
        }
        // 如果没有填写就置空
        else {
          this.formula = `${this.superscript_bottom}^{${this.superscript_top}}`
        } // 使用模板字符串`${}`拼接
      } else if (this.show === 11) {
        // 下标
        if (this.subscript_bottom === '' || this.subscript_top === '') {
          this.formula = ''
        } else {
          this.formula = `${this.subscript_bottom}_{${this.subscript_top}}`
        }
      } else if (this.show === 12) {
        // 上下下标
        if (
          this.allscript_bottom === '' ||
          this.allscript_top === '' ||
          this.allscript_center === ''
        ) {
          this.formula = ''
        } else {
          this.formula = `${this.allscript_center}_{${this.allscript_bottom}}^{${this.allscript_top}}`
        }
      } else if (this.show === 13) {
        // 对数
        if (
          this.log_bottom === '' ||
          this.log_top === '' ||
          this.log_center === ''
        ) {
          this.formula = ''
        } else {
          this.formula = `${this.log_center}_{${this.log_bottom}} {${this.log_top}}`
        }
      } else if (this.show === 2) {
        // 根号
        if (this.sign_left === '' || this.sign_right === '') {
          this.formula = ''
        } else {
          this.formula = `\\sqrt[${this.sign_left}]{${this.sign_right}}`
        }
      } else if (this.show === 3) {
        // 分数
        if (this.fraction_fenzi === '' || this.fraction_fenmu === '') {
          this.formula = ''
        } else {
          this.formula = `\\frac{${this.fraction_fenzi}}{${this.fraction_fenmu}}`
        }
      } else if (this.show === 5) {
        // 弧长
        if (this.widehat === '') {
          this.formula = ''
        } else {
          this.formula = `\\widehat{${this.widehat}}`
        }
      } else if (this.show === 6) {
        // 平均数
        if (this.overline === '') {
          this.formula = ''
        } else {
          this.formula = `\\overline{${this.overline}}`
        }
      } else if (this.show === 7) {
        // 角度
        if (this.angle === '') {
          this.formula = ''
        } else {
          this.formula = `\\angle{${this.angle}}`
        }
      } else if (this.show === 8) {
        // 度数
        if (this.circ === '') {
          this.formula = ''
        } else {
          this.formula = `{${this.circ}}^{\\circ}`
        }
      }

      if (this.fxShow !== true) {
        // 矩阵和弧长只能显示一个第一个没显示就显示第二个
        this.fxShow2 = true
      } else {
        this.fxShow2 = false
      }

      this.getFormale()

      const _this = this
      setTimeout(function () {
        // 公式显示有延时所以这里过700ms再关闭弹窗
        _this.clickShow = false
        _this.clickLoading = false
      }, 500)
    },
    // 最后复杂公式的提交
    fillSubmit () {
      this.fillLoading = true
      var html // 插入的内容

      // 矩阵方程式
      if (this.fxShow === true) {
        // 方程组的格式："\left\{\begin{matrix} 111 \\ 2222  \end{matrix}\right.";
        // 矩阵\begin{matrix} 1222 \\ 2222\\n=1  \end{matrix}
        this.fxAnswer.map((res, index) => {
          if (res.indexOf('img') === -1) {
            // 没有输入公式，直接取出来
            this.fxAnswer2[index] = res
          } else {
            // 有公式把公式图片转出来
            var html = '<div>' + res + '</div>'
            var htmlObj = $(html) // 将字符串转为jquery的dom对象
            var filterObj = htmlObj.find('img')
            if (filterObj.length > 0) {
              // 如果有公式图片，替换
              for (var i = 0; i < filterObj.length; i++) {
                var latex = $(filterObj[i]).attr('data-latex')
                // latex=latex.replace(/\\placeholder/g,"&emsp;");
                $(filterObj[i]).replaceWith(latex)
              }
              this.fxAnswer2[index] = htmlObj.html()
            }
          }
        })

        if (this.showFx) {
          // 方程式
          this.formulaHtml = '\\left\\{\\begin{matrix}'
          this.fxAnswer2.map((res, index) => {
            if (index === 0) {
              this.formulaHtml += res.toString()
            } else {
              this.formulaHtml += '\\\\' + res.toString()
            }
          })
          this.formulaHtml += '\\end{matrix}\\right.'
        } else {
          // 矩阵
          this.formulaHtml = '\\begin{matrix}'
          this.fxAnswer2.map((res, index) => {
            var resString = res.toString()
            if (resString.indexOf(' ') !== -1) {
              // 含有空格
              resString = resString.replace(' ', '&') // 把空格都转为&才能提交是验证出来
            }
            if (index === 0) {
              this.formulaHtml += resString
            } else {
              this.formulaHtml += '\\\\' + resString
            }
          })
          this.formulaHtml += '\\end{matrix}'
        }

        html =
          "<img src='http://latex.codecogs.com/gif.latex?" +
          this.formulaHtml +
          "'  data-latex='" +
          this.formulaHtml +
          "' class='kfformula'  />"
      // eslint-disable-next-line brace-style
      }
      // 弧长，平均数
      else if (this.fxShow2 === true) {
        html = this.widehatHtml
      }

      // 获取之前焦点的位置并插入内容
      this.thisme.execCommand('inserthtml', html)
      this.fxShow = false
      this.fxShow2 = false
      const _this = this
      setTimeout(function () {
        // 公式显示有延时所以这里过700ms再关闭弹窗
        _this.formulaDialogueVisible = false
        _this.fillLoading = false
      }, 700)
    },
    //      平行垂直的点击事件
    Closeformal (num) {
      let html = ''
      let newformal = ''
      if (num === 1) {
        html = '//'
      }
      if (num === 2) {
        html = '\\perp '
      }
      if (num === 3) {
        html = '\\triangle'
      }
      newformal =
        "<img src='http://latex.codecogs.com/gif.latex?" +
        html +
        "' data-latex='" +
        html +
        "' class='kfformula'/>"
      if (num === 4) {
        newformal = '▱'
      } // 直接一个平行四边形的图标
      const _this = this
      setTimeout(function () {
        // 公式显示有延时所以这里过700ms再关闭弹窗
        _this.formulaDialogueVisible = false
      }, 700)
      this.thisme.execCommand('inserthtml', newformal)
    }
  },
  watch: {}
}
</script>

<style scoped>
</style>
